package com.jcompressor.model.config;

import java.io.Serializable;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;

import com.jcompressor.JcompressorContext;
import com.jcompressor.exceptions.JcompressorException;
import com.jcompressor.type.ResourceType;

public class Resource implements Serializable {
	
	private static final long serialVersionUID = 1714659785046162038L;
	
	private String id;
	private String library;
	private String name;
	private String target;
	private Long checksum;
	private String content;
	
	public String getId() {
		return JcompressorContext.getConfigurator().getPropertyExpander().expandProperties(this.id);
	}
	
	public String getLibrary() {
		return JcompressorContext.getConfigurator().getPropertyExpander().expandProperties(this.library);
	}
	
	public String getName() {
		return JcompressorContext.getConfigurator().getPropertyExpander().expandProperties(this.name);
	}
	
	public String getTarget() {
		return JcompressorContext.getConfigurator().getPropertyExpander().expandProperties(this.target);
	}
	
	public Long getChecksum() {
		return this.checksum;
	}
	
	public ResourceType getType() {
		if (StringUtils.isBlank(this.name)) {
			return null;
		}
		
		if (StringUtils.endsWith(this.name, ResourceType.SCRIPT.getExtension())) {
			return ResourceType.SCRIPT;
		}
		else if (StringUtils.endsWith(this.name, ResourceType.STYLE.getExtension())) {
			return ResourceType.STYLE;
		}
		
		throw new JcompressorException("Invalid content-type");
	}
	
	public String getContent() {
		return this.content;
	}
	
	public void setId(final String id) {
		this.id = id;
	}
	
	public void setLibrary(final String library) {
		this.library = library;
	}
	
	public void setName(final String name) {
		this.name = name;
	}
	
	public void setTarget(final String target) {
		this.target = target;
	}
	
	public void setChecksum(final Long checksum) {
		this.checksum = checksum;
	}
	
	public void setContent(final String content) {
		this.content = content;
	}
	
	@Override
	public boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		
		if (obj == null) {
			return false;
		}
		
		if (!(obj instanceof Resource)) {
			return false;
		}
		
		final Resource resource = (Resource)obj;
		if (StringUtils.equals(resource.getId(), this.getId())) {
			return true;
		}
		
		return false;
	}
	
	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return new ToStringBuilder(this)
			.append("ID", this.getId())
			.append("Library", this.getLibrary())
			.append("Name", this.getName())
			.append("Target", this.getTarget())
			.append("Checksum", this.getChecksum())
			.append("Type", this.getType())
			.toString();
	}
	
}